package mybatis.generator.support.parse;

import mybatis.generator.annotation.Column;
import mybatis.generator.annotation.Id;
import mybatis.generator.support.StringUtils;

import java.lang.reflect.Field;
import java.util.*;

/**
 * Created by huangdachao on 2018/6/15 16:06.
 */
public class FieldMeta {
    private Field field;
    private TableColumn tableColumn;
    private boolean insertable = true;
    private boolean updateable = true;
    private List<String> views = new ArrayList<>();
    private List<JoinMeta> joinMeta = new ArrayList<>();

    public FieldMeta(Field field, String defaultTable) {
        this.field = field;
        this.tableColumn = new TableColumn();
        Column col = field.getAnnotation(Column.class);
        Id id = field.getAnnotation(Id.class);

        if (col != null) {
            this.tableColumn.table = StringUtils.isEmpty(col.table()) ? defaultTable : col.table();
            this.tableColumn.tblAlias = col.tblAlias();
            this.tableColumn.column = StringUtils.isEmpty(col.column()) ? StringUtils.snakeCase(field.getName()) : col.column();
            this.insertable = col.insertable();
            this.updateable = col.updateable();
            this.views = Arrays.asList(col.view());
        } else if (id != null) {
            this.tableColumn.table = defaultTable;
            this.tableColumn.column = id.column().isEmpty() ? StringUtils.snakeCase(field.getName()) : id.column();
            this.insertable = id.insertable();
            this.updateable = id.updateable();
        } else {
            this.tableColumn.table = defaultTable;
            this.tableColumn.column = StringUtils.snakeCase(field.getName());
        }
    }

    public Field getField() {
        return field;
    }

    public TableColumn getTableColumn() {
        return tableColumn;
    }

    public boolean isInsertable() {
        return insertable;
    }

    public boolean isUpdateable() {
        return updateable;
    }

    public List<String> getViews() {
        return views;
    }

    public List<JoinMeta> getJoinMeta() {
        return joinMeta;
    }
}
